<template>
  <!--查看审批-->
  <el-dialog :close-on-click-modal="false" title="查看审批" :beforeClose="handleClose" :visible.sync="dialogVisible"
    width="800px">
    <el-form :model="form" ref="form" size="small" :rules="rules" label-width="100px">
      <el-descriptions :labelStyle="{ width: '100px'}" :column="2" size="small" border  >
        <el-descriptions-item>
          <template slot="label">审批状态</template>
          {{ info.checkStateStr }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">审批类型</template>
          {{ info.checkTypeStr }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">申请人</template>
          {{ info.applyUserName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">申请时间</template>
          {{ info.applyTime }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">当前审批人</template>
          {{ info.checkUserName }}
        </el-descriptions-item>
      </el-descriptions>
      <div style="font-weight: bold;padding:10px 0">审批内容</div>
      <el-descriptions :labelStyle="{ width: '100px'}" :column="2" size="small" border  >

        <el-descriptions-item>
            <template slot="label">客户编号</template>
            {{ info.customerNumber }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">客户名称</template>
            {{ info.customerName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">合同公司</template>
            {{ info.fromCompany }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">合同号</template>
            {{ info.orderSn }}
          </el-descriptions-item>
           <el-descriptions-item v-if="info.checkType == 'payTypeApply' || info.checkType == 'WXBankAccountApply'">
            <template slot="label">原结算方式</template>
            <div>{{ info.transactionType|fifPayTypes }}</div>
            <div>{{ info.orderRemark }}</div>
          </el-descriptions-item>
          <el-descriptions-item v-if="info.checkType == 'payTypeApply' || info.checkType == 'WXBankAccountApply'">
            <template slot="label">申请结算方式</template>
            <div>{{ info.payType|fifPayTypes }}</div>
            <div>{{ info.checkContent }}</div>
          </el-descriptions-item>
          <el-descriptions-item v-if="info.checkType == 'delaySendApply'">
            <template slot="label">原关闭时间</template>

            <div style="color:REd">{{ info.oldCloseDate }}</div>
          </el-descriptions-item>
          <el-descriptions-item v-if="info.checkType == 'delaySendApply'">
            <template slot="label">延期关闭时间</template>
            <div style="color:REd">{{ info.nowCloseDate }}，延迟{{info.delayDaysNum}}天</div>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">合同数量</template>
            {{ info.goodsNum }}吨
          </el-descriptions-item>
          <el-descriptions-item v-if="info.checkType == 'delaySendApply'">
            <template slot="label">未发货数量</template>
            {{ info.unSendGoodsNum }}吨
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">合同金额</template>
            ￥{{ info.goodsAmount }}
          </el-descriptions-item>
          <el-descriptions-item v-if="info.checkType == 'delaySendApply'">
            <template slot="label">未支付金额</template>
            ￥{{ info.unPaidAmount }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">订单预估毛利</template>
            ￥{{ info.orderAboutProfit }}
          </el-descriptions-item>
          <el-descriptions-item v-if="info.checkType == 'payTypeApply' || info.checkType == 'WXBankAccountApply'">
            <template slot="label">贷款金额</template>
            ￥{{ info.loanAmount }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">订单运费</template>
            ￥{{ info.orderFreight }}
          </el-descriptions-item>
        <el-descriptions-item v-if="info.checkType == 'delaySettleOrderApply'">
          <template slot="label">结算方式</template>
          {{ info.orderRemark  }}
        </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">备注</template>
            {{ info.remark }}
          </el-descriptions-item>
        </el-descriptions>
      <div style="font-weight: bold;padding:10px 0">商品信息</div>
      <el-table :data="info.orderGoodsList" size="mini" border style="width: 100%;margin:12px 0" :span-method="objectSpanMethod" v-if="info.checkType == 'delaySettleApply'">
        <el-table-column min-width="150" label="品名牌号" align="center" prop="goodsName">
          <template slot-scope="scope"> {{scope.row.goodsName}}/{{scope.row.goodsSn}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="本次结算数量"
          min-width="100">
          <template slot-scope="scope">
            {{scope.row.applyNum}}
          </template>
        </el-table-column>
        <el-table-column
          label="本次结算单价"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.applyPrice}}
          </template>
        </el-table-column>
        <el-table-column
          label="结算吨毛利"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.perGoodsProfit}}
          </template>
        </el-table-column>
        <el-table-column
          label="采销盈亏占比"
          min-width="180"
          align="center">
          <template slot-scope="scope">
            销售：{{(scope.row.settleSaleProfitRate*100).toFixed(0) }}% / 采购：{{ (scope.row.settlePurchaseProfitRate*100).toFixed(0) }}%
          </template>
        </el-table-column>
        <el-table-column
          label="销售预估吨毛利"
          min-width="120"
          align="center">
          <template slot-scope="scope">
            {{scope.row.settleSaleProfit}}
          </template>
        </el-table-column>
        <el-table-column label="采购预估吨毛利" min-width="120" align="center">
          <template slot-scope="scope">
            {{scope.row.settlePurchaseProfit}}
          </template>
        </el-table-column>
        <el-table-column  label="备注" min-width="150" align="center">
          <template slot-scope="scope">
            {{scope.row.remark}}
          </template>
        </el-table-column>
      </el-table>

      <el-table
        v-else
        size="mini"
        :data="info.orderGoodsList"
        border
        style="width: 100%; padding: 0;"
      >
        <el-table-column min-width="150" label="品名牌号" align="center" >
          <template slot-scope="scope"> {{scope.row.goodsName}}
          </template>
        </el-table-column>
        <el-table-column min-width="100" label="商品单价" align="center" >
          <template slot-scope="scope"> {{scope.row.goodsPrice}}
          </template>
        </el-table-column>
        <el-table-column min-width="100" label="采购报价" align="center" >
          <template slot-scope="scope"> {{scope.row.price}}
          </template>
        </el-table-column>
        <el-table-column min-width="100" label="预估毛利" align="center" >
          <template slot-scope="scope"> {{scope.row.aboutProfit}}
          </template>
        </el-table-column>
        <el-table-column min-width="150" label="采购预计发货日期" align="center" >
          <template slot-scope="scope"> {{scope.row.sendDate}}
          </template>
        </el-table-column>
        <el-table-column min-width="150" label="采购发货完成日期" align="center" >
          <template slot-scope="scope"> {{scope.row.endSendDate}}
          </template>
        </el-table-column>
        <el-table-column min-width="100" label="杂费(装卸费)" align="center" >
          <template slot-scope="scope"> {{scope.row.consultation}}
          </template>
        </el-table-column>
        <el-table-column min-width="100" label="发货方式" align="center" >
          <template slot-scope="scope"> {{scope.row.sendType}}
          </template>
        </el-table-column>
      </el-table>

      <div v-if="info.checkType == 'payTypeApply' || info.checkType == 'WXBankAccountApply'">
        <div style="font-weight: bold;padding:10px 0" >客户情况</div>
        <el-descriptions :labelStyle="{ width: '150px'}" :column="2" size="small" border  >
          <el-descriptions-item>
            <template slot="label">客户是否有未清款项</template>
            {{ info.isArrears==1 ?'是':'否' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="info.arrearsRemark">
            <template slot="label">未清款项说明</template>
            {{ info.arrearsRemark }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">客户账期违约情况</template>
            <span v-if="info.payBreakCount>0" style="color:#ff6600;">存在账期违约,历史违约次数为{{ info.payBreakCount }}次</span>
            <span v-else>无违约</span>
          </el-descriptions-item>
          <el-descriptions-item v-if="info.reputation">
            <template slot="label">客户信誉</template>
            {{info.reputation}}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <el-form-item label="上传延期补充协议："  v-if="info.isCheckUser == 1 && info.checkType == 'delaySendApply' && info.checkState == 50" label-width="150px" style="margin-top:10px">
          <el-upload action="https://upload.qiniup.com"
                     :on-exceed="handleExceed"
                     :http-request="sliderRequest" :limit="1"  :file-list="fileList" :on-remove="delfile" list-type="text">
            <el-button size="small" type="primary">点击上传</el-button>
            <el-button type="text" @click.stop="downXY" v-if="info.originSideAgreementUrl != ''">下载补充协议模版</el-button>
          </el-upload>
      </el-form-item>

      <el-form-item label="" label-width="17px" style="margin-top:10px" v-if="info.isEnableNoDeposit == 1">
        <el-checkbox v-model="isEnableNoDeposit">定金修改为0</el-checkbox>
      </el-form-item>

      <el-form-item label="审批备注：" v-if="info.isCheckUser == 1" prop="checkRemark">
        <el-input type="textarea" v-model="form.checkRemark" :row="3" clearable style="width: 400px;"></el-input>
      </el-form-item>
    </el-form>

    <div class="btnStyle" style="margin-top:20px;">
      <el-button
        v-if="info.sideAgreementUrl != ''"
        type="success"
        @click="seeXY"
        size="small">查看补充协议</el-button>
      <el-button
        type="success"
        @click="toSee"
        size="small">合同预览</el-button>
      <el-button
        type="primary"
        v-if="info.isCheckUser==1"
        :loading="agreeLoading"
        @click="handleConfirm(1)"
        size="small">审批通过</el-button>
      <el-button
        type="info"
        v-if="info.isCheckUser==1"
        :loading="btnLoading"
        @click="handleConfirm(0)"
        size="small">审批拒绝</el-button>
     </div>
     <div style="padding:10px 0"><el-divider content-position="left">审批操作流程</el-divider></div>
     <el-timeline :reverse="reverse">
      <el-timeline-item
        v-for="(activity, index) in activities"
        :key="index"
        >
        <div>
          <span>{{ activity.userName }}</span>
          <span>{{ activity.createTime }}</span>
        </div>
        <div>
        {{ activity.content }}
        </div>
      </el-timeline-item>
    </el-timeline>
  </el-dialog>
</template>
<script>
import { getCheckDetailAPI, orderCheckAPI } from '@/api/purchase.js'
import {getQiniuToken,} from '@/api/partner'
import { formatDate } from '@/utils/date';
import store from '@/store'
import { mapGetters } from 'vuex'
import axios from "axios";
const defaultForm = {
  checkId:"",
  action: "",
  checkRemark:"",
  sideAgreementUrl:'',
};
export default {
  name: "handleApplyCheck",
  data() {
    return {
      dialogVisible: false,
      btnLoading: false,
      agreeLoading:false,
      form: JSON.parse(JSON.stringify(defaultForm)),
      info: {},
      nameStyle: {
        width: '100px',
      },
      rules: {
        checkRemark: [{ required: true, message: '请输入审批备注', trigger: 'blur' }],
      },
      reverse: false,
      activities: [],

      uploadToken:'',
      imgDomain:'',
      fileList:[],
      isEnableNoDeposit:false
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  components: {

  },
  created() {

  },
  filters: {
     fifPayTypes(val) {
      if (val == 'BANK_PAY') {
        return '款到发货'
      } else if (val == 'COD_PAY') {
        return '货到付款'
      } else if (val == 'COD_PAY2') {
        return '货到票到付款'
      } else if (val == 'HONOUR_PAY') {
        return '承兑结算'
      } else if (val == 'XISHANG_PAY') {
        return '摩塑白条'
      } else {
        return val
      }
    },
  },
  methods: {
    objectSpanMethod({ row, column, rowIndex, columnIndex }){
      let bhName = ['goodsName']
      if(bhName.indexOf(column.property) != -1){
        if (row.isHb) {
          return {
            rowspan: row.hbnum,
            colspan: 1
          };
        }else{
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }else{
        return {
          rowspan: 1,
          colspan: 1
        };
      }
    },
    handleExceed(){
      this.$message.error('只能上传一个文件');
    },
    delfile(){
      this.fileList = []
      this.form.sideAgreementUrl = ''
    },
    downXY(){
      window.open(this.info.originSideAgreementUrl, '_blank');
    },
    //获取七牛TOKEN
    getUploadToken(){
      getQiniuToken().then((res)=>{
        this.uploadToken = res.token;
        this.imgDomain = res.domain
      })
    },
    //上传文件重写
    sliderRequest(upload) {
      // 文件上传自行处理上传
      // 创建FormData对象 添加相关上传参数
      const formData = new FormData()
      // 文件对象
      formData.append('file', upload.file)
      // key 文件名处理，这样的话七牛会识别文件时什么类型
      let timestamp=new Date().getTime();
      let fileName = timestamp + upload.file.name
      formData.append('key', fileName)
      // token
      formData.append('token', this.uploadToken)//这个postData,要在data数据里面进行定义的，，，我这里调接口使用的是vue的方式
      // 上传文件
      // onUploadProgress 查看axios文档 https://github.com/axios/axios
      axios.post("https://upload.qiniup.com", formData, {
        onUploadProgress: (event) => {
          // 监听上传进度
          event.percent = event.loaded / event.total * 100
          upload.onProgress(event)
        }
      }).then((response) => {
        if (response.status === 200) {
          let res = response.data;
          this.form.sideAgreementUrl = this.imgDomain+res.key;
          this.fileList = [{name:this.imgDomain+res.key,url:this.imgDomain+res.key}]
        }else{
          this.$message.error('上传失败');
        }
      }).catch((err) => {
        // 调用组件上传失败方法
        this.$message.error('上传失败');
      })
    },
    //查看补充协议
    seeXY(){
      window.open(this.info.sideAgreementUrl, '_blank');
    },
    // 合同预览
    toSee() {
      // this.$router.push({
      //   name: "printing",
      //   query: { id: this.info.orderId, type: 1, isPums: 1 },
      //   target:'_blank'
      // })
      const url = this.$router.resolve({
        name: 'printing',
        query: { id: this.info.orderId, type: 1, isPums: 1 }
      }).href;
      window.open(url, '_blank');
    },
    //显示
    showPop(item) {
      this.dialogVisible = true;
      this.getUploadToken()
      getCheckDetailAPI({
        checkId:item.checkId
      }).then((res) => {
        this.info = res
        this.form = JSON.parse(JSON.stringify(defaultForm))
        this.fileList = []
        this.form.checkId=res.checkId
        this.activities=res.logList
        let messageContent = res.messageContent != '' ? JSON.parse(res.messageContent) : null
        if(res.checkType == 'delaySettleApply'){
          this.hblist(messageContent)
        }
        this.info.goodsAmount= messageContent.goodsAmount
        this.info.loanAmount = messageContent.loanAmount
        this.info.remark = messageContent.remark
        this.info.goodsNum = messageContent.goodsNum
        this.info.orderRemark = messageContent.orderRemark  //原结算方式
        this.info.unSendGoodsNum = messageContent.unSendGoodsNum;
        this.info.unPaidAmount = messageContent.unPaidAmount;
        this.info.oldCloseDate = messageContent.oldCloseDate;
        this.info.nowCloseDate = messageContent.nowCloseDate
        this.info.delayDaysNum = messageContent.delayDaysNum
      })
    },
    hblist(response){
      this.info.orderGoodsList = []
      response.goodsList.forEach((el,index)=>{
        el.applyList.forEach((ee,index2)=>{
          let c={}
          for(let key1 in el){
            if(key1 != 'useGoodsList'){
              c[key1] = el[key1]
            }
          }
          for(let key2 in ee){
            c[key2] = ee[key2]
          }
          if(index2 == 0){
            c.hbnum = el.applyList.length
            c.isHb = true
          }else{
            c.hbnum = 0
            c.isHb = false
          }
          this.info.orderGoodsList.push(c)
        })
        if(el.applyList.length == 0){
          let c={}
          for(let key1 in el){
            if(key1 != 'applyList'){
              c[key1] = el[key1]
            }
          }
          c.hbnum = 1
          c.isHb = true
          this.info.orderGoodsList.push(c)
        }
      })
    },
    //关闭
    handleClose() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    //提交
    handleConfirm(type) {
      let data = JSON.parse(JSON.stringify(this.form));
      if (type == 0) {
        data.action='refuseCheck'
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.btnLoading = true;
            orderCheckAPI(data).then((res) => {
              this.btnLoading = false;
              this.handleClose();
              this.$emit('upload')
            }).catch(() => {
              this.btnLoading = false;
            })
          }
        })
      } else if (type == 1) {
        if (this.info.checkState == 0) {
          data.action = 'departUserCheck'
        } else if (this.info.checkState == 40) {
          data.action = 'bossCheck'
        }else if (this.info.checkState == 10) {
          data.action = 'pChargeUserCheck'
        } else if (this.info.checkState == 20) {
          data.action = 'pDepartUserCheck'
        } else if (this.info.checkState == 25) {
          data.action = 'financeUserCheck'
        } else if (this.info.checkState == 30 && this.info.checkType == 'WXBankAccountApply') {
          data.action = 'fDepartUserCheck'
        } else if (this.info.checkState == 30 && (this.info.checkType == 'payTypeApply' || this.info.checkType == 'delaySettleOrderApply' )) {
          data.action = 'financeUserCheck'
        } else if (this.info.checkState == 35 && this.info.checkType == 'payTypeApply') {
          data.action = 'fCashierUserCheck'
        }else if (this.info.checkState == 50) {
          data.action = 'uploadSideAgreement'
        }else if (this.info.checkState == 55) {
          data.action = 'sideAgreementCheck'
        }else if (this.info.checkState == 8) {
          data.action = 'saleUserCheck'
        }

        if(this.info.checkState == 50 && this.form.sideAgreementUrl==''){
          this.$message({
            message: '请上传补充协议',
            type: 'warning',
            duration: 1000
          });
          return false
        }
        if(this.isEnableNoDeposit){
          data.isEnableNoDeposit = 1
        }
        this.agreeLoading = true;
        orderCheckAPI(data).then((res) => {
           this.agreeLoading = false;
           this.handleClose();
           this.$emit('upload')
         }).catch(() => {
           this.agreeLoading = false;
         })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.btnStyle{
  text-align: center;
}
.checkBoxStyle{
  font-size: 12px;
  color: #606266;;
  padding: 8px 30px 8px 40px;
  .smallBoxStyle{
    height: 32px;
  }
  .ckRemarkStyle{
    display: flex;
    vertical-align: top;
  }
}
</style>
